package wnhz.com.business.groupshop.fragment;

import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.youth.banner.Banner;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.groupshop.adapter.MainGoodsAdapter;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.base.BaseFragment;
import wnhz.com.business.base.BaseRecyclerAdapter;
import wnhz.com.business.groupshop.bean.GoodsBean;
import wnhz.com.business.constants.EXTRA;
import wnhz.com.business.groupshop.bean.HomeIndexBean;
import wnhz.com.business.groupshop.ui.GoodsDetailsActivity;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.netcallback.JsonCallback;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.decoration.DividerGridItemDecoration;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.uitls.GlideImageLoader;
import wnhz.com.business.view.MyRecyclerView;
import wnhz.com.business.view.ScrollGridLayoutManager;
import wnhz.com.business.view.TranslucentActionBar;

public class HomeFragment1 extends BaseFragment implements ActionBarClickListener, BaseRecyclerAdapter.OnDataLoadFinish {
    private static final String TAG = "HomeFragment1";

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.sliding_tabs)
    TabLayout sliding_tabs;
    @BindView(R.id.recycler)
    MyRecyclerView recyclerView;
    @BindView(R.id.empty_layout)
    LinearLayout emptyLayout;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;

    @BindView(R.id.ll_discount)
    LinearLayout ll_discount;
    @BindView(R.id.ll_fruits)
    LinearLayout ll_fruits;
    @BindView(R.id.ll_brands)
    LinearLayout ll_brands;
    @BindView(R.id.ll_love)
    LinearLayout ll_love;
    @BindView(R.id.ll_home_cate1)
    LinearLayout ll_home_cate1;
    @BindView(R.id.ll_home_cate2)
    LinearLayout ll_home_cate2;

    private View view;
    private BaseActivity activity;
    private List<String> imageUrls = new ArrayList<>();
    private MainGoodsAdapter mainGoodsAdapter;
    private String cateId = "";
    private String page = "0";
    private HomeIndexBean homeIndexBean = new HomeIndexBean();
    private List<HomeIndexBean.InfoBean.CateListBean> cateListBeen = new ArrayList<>();
    private List<HomeIndexBean.InfoBean.GoodsBean> goodsBeanList = new ArrayList<>();
    private List<HomeIndexBean.InfoBean.BannerBean> bannerBeanList = new ArrayList<>();

    private BaseRVAdapter goodsadapter;
    public static HomeFragment1 newInstance() {
        HomeFragment1 homeFragment1 = new HomeFragment1();
        return homeFragment1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home_fragment1, container, false);
        ButterKnife.bind(this, view);
        activity = (BaseActivity) getActivity();
        actionbar.setData("拼团商城", 0, null, 0, null, 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        recyclerView.setLayoutManager(new GridLayoutManager(activity,2,GridLayoutManager.VERTICAL,false));
        recyclerView.addItemDecoration(new DividerGridItemDecoration(20));
        loadData();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
//        loadData();
    }

    /**
     * 获取首页数据
     */
    private void loadData() {
        cateListBeen.clear();
        goodsBeanList.clear();
        bannerBeanList.clear();
        Map<String,String> map = new HashMap<>();
        if (TextUtils.isEmpty(MyApplication.getInstance().getInfoBean().getToken())){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }else {
            map.put("token", MyApplication.getInstance().getInfoBean().getToken());
            map.put("cateId", cateId);
            map.put("page", page);
            map.put("goods_type", "1");//1.拼团  2.返利  3.免费
            OkGo.<String>post(Url.HOME_INDEXDADA)
                    .tag(this)
                    .params(map, false)
                    .execute(new DialogCallback<String>(activity) {

                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.e("首页数据", response.body().toString());
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String res = jsonObject.optString("re");
                            if (res.equals("1")){
                                Gson gson = new Gson();
                                homeIndexBean = gson.fromJson(response.body(),HomeIndexBean.class);
                                cateListBeen = homeIndexBean.getInfo().getCate_list();
                                goodsBeanList = homeIndexBean.getInfo().getGoods();
                                bannerBeanList = homeIndexBean.getInfo().getBanner();
                                initTabLayout();
                                initView();
                                initBanner();
                            }else{
                                ToastUtils.showToast(activity,"暂无数据");
                            }
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
        }
    }

    private void initBanner() {
        imageUrls.clear();
        for (int i = 0; i < bannerBeanList.size(); i++) {
            imageUrls.add(bannerBeanList.get(i).getPic());
        }
        banner.setImageLoader(new GlideImageLoader());
        banner.setImages(imageUrls);
        banner.start();
    }


    private void initTabLayout() {
        List<String> templist = new ArrayList<>();
        templist.clear();
        for (int i = 0; i < cateListBeen.size(); i++) {
            templist.add(cateListBeen.get(i).getClassname());
            sliding_tabs.addTab(sliding_tabs.newTab().setText(templist.get(i)));
        }

        sliding_tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0){
                    ll_home_cate1.setVisibility(View.VISIBLE);
                    ll_home_cate2.setVisibility(View.VISIBLE);
                }else {
                    ll_home_cate1.setVisibility(View.GONE);
                    ll_home_cate2.setVisibility(View.GONE);
                }
                cateId = cateListBeen.get(tab.getPosition()).getCate_id();
                reLoadData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initView() {

        goodsadapter = new BaseRVAdapter(activity, goodsBeanList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_goods;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                Glide.with(activity).load(goodsBeanList.get(position).getLogo_pic()).into(holder.getImageView(R.id.iv_img));
                holder.setTextView(R.id.tv_title,goodsBeanList.get(position).getGoods_name());
                holder.setTextView(R.id.tv_money, goodsBeanList.get(position).getGroup_price());
                holder.setTextView(R.id.tv_collectNum,goodsBeanList.get(position).getSales());
                holder.getView(R.id.ll_boss).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(GoodsDetailsActivity.createIntent(activity, goodsBeanList.get(position).getGoods_id(), "", ""));
                    }
                });
            }
        };
        recyclerView.setAdapter(goodsadapter);

//        mainGoodsAdapter = new MainGoodsAdapter(activity, goodsBeanList);
//        mainGoodsAdapter.setOnDataLoadFinish(this);
//        mainGoodsAdapter.loadDataFirstTime();
//
//        ScrollGridLayoutManager gridManager = new ScrollGridLayoutManager(getActivity(), 2,
//                LinearLayoutManager.VERTICAL, false);  //自定义解决RecyclerView在ScrollView中滑动卡顿现象
//        gridManager.setScrollEnabled(false);
//
//        recyclerView.setLayoutManager(gridManager);
//        recyclerView.addItemDecoration(new DividerGridItemDecoration(20));//分割线
//        recyclerView.setAdapter(mainGoodsAdapter);
//
//        gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int position) {
//                int spansize = 1;
//                switch (mainGoodsAdapter.getItemViewType(position)) {
//                    case EXTRA.TYPE_FOOTER:
//                        spansize = 2;
//                        break;
//                    case EXTRA.TYPE_HEADER:
//                        spansize = 2;
//                        break;
//                }
//                return spansize;
//            }
//        });
//
//        mainGoodsAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(View view, Object data) {
//                startActivity(GoodsDetailsActivity.createIntent(activity, "", "", ""));
//            }
//        });
    }

    /**
     * 重新获取首页数据
     */
    private void reLoadData() {
        goodsBeanList.clear();
        Map<String,String> map = new HashMap<>();
        if (TextUtils.isEmpty(MyApplication.getInstance().getInfoBean().getToken())){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }else {
            map.put("token", MyApplication.getInstance().getInfoBean().getToken());
            map.put("cateId", cateId);
            map.put("page", page);
            map.put("goods_type", "1");//1.拼团  2.返利  3.免费
            OkGo.<String>post(Url.HOME_INDEXDADA)
                    .tag(this)
                    .params(map, false)
                    .execute(new DialogCallback<String>(activity) {

                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.e("首页数据", response.body().toString());
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String res = jsonObject.optString("re");
                            if (res.equals("1")){
                                Gson gson = new Gson();
                                homeIndexBean = gson.fromJson(response.body(),HomeIndexBean.class);
                                goodsBeanList = homeIndexBean.getInfo().getGoods();
                                initView();
                            }else{
                                ToastUtils.showToast(activity,"暂无数据");
                                initView();
                            }
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
        }
    }

    @Override
    public void onLeftClick() {

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }

    @Override
    public void loadDataFinished(int datasLength) {
        if (datasLength == 0) {
            emptyLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            emptyLayout.setVisibility(View.GONE);
        }
    }
}
